<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
	<head>
		<meta charset="utf-8">
		<title>角色管理</title>
		<link href="/pear_layui/component/pear/css/pear.css" rel="stylesheet" />
		<style>
			/* zdy主题风格*/
			.dtree-zdy-item-this{background-color: #c2c2c2!important;} /* 当前选中行样式*/
			.dtree-zdy-item:hover{background-color: #f2f2f2!important;} /* 行悬停样式*/
			.dtree-zdy-item cite{font-size:14px!important;} /* 行文字样式*/
			.dtree-zdy-item:hover cite{color:#5FB878!important;} /* 行悬停文字样式*/
			.dtree-zdy-dtreefont{font-size: 18px!important;} /* 一级图标、二级图标、复选框样式*/
			.dtree-zdy-ficon{color:#009f95!important;}  /*一级图标特定样式*/
			.dtree-zdy-icon{color:#009f95!important;}  /*二级图标特定样式*/
			.dtree-zdy-checkbox:hover{color:#5FB878!important;}  /*复选框悬停样式*/
			.dtree-zdy-choose{color:#5FB878!important;} /* 复选框选中样式*/
		</style>
	</head>
	<body class="pear-container">
		<div class="layui-card">
			<div class="layui-card-body">
				<form class="layui-form" action="">
					<div class="layui-form-item">
						<div class="layui-form-item layui-inline">
							<label class="layui-form-label">名称</label>
							<div class="layui-input-inline">
								<input type="text" name="name" class="layui-input">
							</div>
						</div>
						<div class="layui-form-item layui-inline">
							<label class="layui-form-label">编码</label>
							<div class="layui-input-inline">
								<input type="text" name="code" class="layui-input">
							</div>
						</div>
						<div class="layui-form-item layui-inline">
							<button class="pear-btn pear-btn-md pear-btn-primary" lay-submit lay-filter="role-query">
								<i class="layui-icon layui-icon-search"></i>
								查询
							</button>
							<button type="reset" class="pear-btn pear-btn-md">
								<i class="layui-icon layui-icon-refresh"></i>
								重置
							</button>
						</div>
					</div>
				</form>
			</div>
		</div>
		<div class="layui-card">
			<div class="layui-card-body">
				<table id="role-table" lay-filter="role-table"></table>
			</div>
		</div>

		<!--添加和修改窗口-->
		<div id="addOrUpdateWindow" style="display: none;padding: 20px 50px;">
				<form class="layui-form" action="" id="dataFrm" lay-filter="dataFrm">
				<div class="layui-row">

					<div class="layui-col-md5">
						<legend style="text-align: center;color: #009f95;margin-bottom: 10px">请选择菜单</legend>
						<div style="border-top: 1px solid #009f95;padding: 10px;">
							<ul id="MenuTreeList" class="dtree" data-id="0"></ul>
						</div>
					</div>

					<div class="layui-col-md7">
						<legend style="text-align: center;color: #009f95;margin-bottom: 10px">请输入角色</legend>
							<!-- 隐藏域，保存用户id -->
							<input type="hidden" name="id" value="">
							<div class="layui-form-item">
								<label class="layui-form-label">名称</label>
								<div class="layui-input-block">
									<input type="text" name="name" id="roleName" lay-verify="required" autocomplete="off" placeholder="请输入角色名称" class="layui-input">
								</div>
							</div>
							<div class="layui-form-item">
								<label class="layui-form-label">编码</label>
								<div class="layui-input-block">
									<input type="text" name="code" id="roleCode" lay-verify="required" autocomplete="off" placeholder="请输入角色编码，默认以R_开头！" class="layui-input">
								</div>
							</div>
							<div class="layui-form-item layui-form-text">
								<label class="layui-form-label">描述</label>
								<div class="layui-input-block">
									<textarea placeholder="请输入..." name="description" class="layui-textarea"></textarea>
								</div>
							</div>
					</div>
				</div>
				</form>
		</div>

		<script type="text/html" id="role-toolbar">
			<button class="layui-btn layui-btn-normal layui-btn-sm data-add-btn" lay-event="add"><i
							class="layui-icon layui-icon-add-1"></i>添加
			</button>
		</script>
		
		<script type="text/html" id="role-bar">
			<a class="layui-btn layui-btn-xs data-count-edit" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
			<a class="layui-btn layui-btn-xs layui-btn-danger data-count-delete" lay-event="remove"><i
							class="layui-icon layui-icon-delete"></i>删除</a>
		</script>

		<script src="/pear_layui/component/layui/layui.js"></script>
		<script src="/pear_layui/component/pear/pear.js"></script>
		<script>
				layui.extend({
					dtree:"/pear_layui/layui_ext/dtree/dtree"
				}).use(['table','form','jquery','dtree'],function () {
		        let table = layui.table;
		        let form = layui.form;
		        let $ = layui.jquery;
		        let dtree = layui.dtree;

		        let cols = [
		            [
										{field: 'id', hide: true},
		                {title: '名称', field: 'name', align:'center'},
		                {title: '编码', field: 'code', align:'center'},
										{title: '创建时间', field: 'gmtCreate', align:'center',sort: true},
		                {title: '描述', field: 'description', align:'center',templet:function (b) {
		                		if(b.description == null || b.description == ''){
		                			return '暂无';
												}
		                		return b.description;}},
		                {title: '操作', toolbar: '#role-bar', align:'center'}
		            ]
		        ];

		        //渲染表格数据
						let tableIns = table.render({
		            elem: '#role-table',
		            url: '/role/findRole',
		            page: true ,
								limit: 8,
								limits: [8, 16, 32, 64, 128, 256, 512],
		            cols: cols ,
		            skin: 'line',
		            toolbar: '#role-toolbar',
		            defaultToolbar: [{
								title: '刷新',
		                layEvent: 'refresh',
		                icon: 'layui-icon-refresh',
		            }, 'filter', 'print', 'exports'],
								done: function (res, curr, count) {
									//判断当前页码是否是大于1并且当前页的数据量为0
									if (curr > 1 && res.data.length == 0) {
										var pageValue = curr - 1;
										//刷新数据表格的数据
										tableIns.reload({
											page: {curr: pageValue}
										});
									}
								}
		        });

						form.on('submit(role-query)', function(data){
							table.reload('role-table', {
								where: data.field,
								page: {
									curr: 1
								}
							})
							return false;
						});

		        table.on('tool(role-table)', function(obj){
		            if(obj.event === 'remove'){
		                window.remove(obj);
		            } else if(obj.event === 'edit'){
		                window.edit(obj);
		            }
		        });
		
		        table.on('toolbar(role-table)', function(obj){
		            if(obj.event === 'add'){
		                window.add();
		            } else if(obj.event === 'refresh'){
		                window.refresh();
		            }
		        });

						//初始化菜单树列表
						function initdtree(roleId){
							let param = 0;
							if(roleId != undefined){
								param = roleId;
							}
							//渲染角色菜单树
							var menuTree = dtree.render({
								elem: "#MenuTreeList",//绑定ul标签的ID属性值
								url: "/role/initRoleMenuTree/" + param, //请求地址
								dataStyle: "layuiStyle", //使用layui风格的数据格式
								dataFormat: "list", //配置data的风格为list
								response:{message:"msg",statusCode:0}, //修改response中返回数据的定义
								checkbar:true,//开启复选框
								line: true,  // 显示树线
								menubar:true,//组件上方提示图标
								skin: "zdy",  // 自定义风格
								//nodeIconArray:{"3":{"open":"dtree-icon-xiangxia1","close":"dtree-icon-xiangyou"}},
								leafIconArray:{"11":"dtree-icon-evaluate"},  // 自定义扩展的二级最后一级图标，从11开始
								icon: ["0","11"], // 使用
								menubarFun: {
									remove: function(checkbarNodes){
										layer.msg('不可删除');
										console.log(checkbarNodes);
										return true;
									}
								}
							});
						}

		        //添加角色
		        window.add = function(){
							//初始化菜单树列表
							initdtree();
							addAndEditOption(undefined,'添加角色','save');
		        };

						function addAndEditOption(obj,title,type){
							let loadIndex = layer.load(1);
							mainIndex = layer.open({
								type: 1,
								title: title,
								shade: 0.1,
								area: ['700px', '400px'],//宽高
								content: $('#addOrUpdateWindow'),
								btn: ['提交', '取消']
								//确定按钮点击事件
								,yes: function(index, layero){
									//表单验证
									if($('#roleName').val().trim() == ''){
										layer.msg('请输入角色名称');
										$('#roleName').focus();
										return false;
									}
									if($('#roleCode').val().trim() == ''){
										layer.msg('请输入角色编码');
										$('#roleCode').focus();
										return false;
									}
									let loadIndex = layer.load(1);
									let params = dtree.getCheckbarNodesParam("MenuTreeList");
									let mIdArr = [];
									for(let i of params){
										mIdArr.push(i.nodeId);
									}
									//将数组变为字符串
									let mIds = mIdArr.join(',');
									//ajax提交表单
									let roleData = $('#dataFrm').serialize();
									$.post("/role/"+ type +"?mids="+mIds,roleData,function (result) {
										layer.close(loadIndex);
										if(result.success){
											layer.msg(result.message,{'icon':1});
											layer.close(mainIndex);//关闭窗口
											tableIns.reload();//刷新表格
										}else{
											layer.msg(result.message,{'icon':2,anim: 6});
										}
									},'json');
								},
								//成功打开面板函数
								success: function () {
									$("[name='name']").focus();
									layer.close(loadIndex);
									//清空表单数据
									$('#dataFrm')[0].reset();
									if(type == 'edit'){
										//给修改表单赋值
										form.val('dataFrm', obj.data);
									}
								}
							});
						}
						//编辑角色
		        window.edit = function(obj){
							//初始化编辑菜单树列表
							initdtree(obj.data.id);
							addAndEditOption(obj,'编辑角色','edit');
		        };

						//角色删除
		        window.remove = function(obj){
		        	//先检查该角色下是否有对应的用户
		            $.post("/role/checkIfExistUser/"+ obj.data['id'],function (result) {
		            	if(result.exist){
										layer.alert(result.message,{icon:0});
									}else{
										layer.confirm('确定要删除名称为'+ obj.data['name'] +'的角色及所属菜单关系表中的数据吗？', {icon: 3, title:'提示'}, function(index){
											let loading = layer.load(1);
											$.post("/role/delete/" + obj.data['id'],function (result) {
												layer.close(loading);
												if(result.success){
													layer.close(index);
													tableIns.reload();
													//obj.del();
													layer.msg(result.message,{icon:1});
												}else{
													layer.msg(result.message,{icon:2,anim:6});
												}
											},'json');
										});
									}
		            },'json');
		        }

		        window.refresh = function(){
		            table.reload('role-table');
		        }
		    })
		</script>
	</body>
</html>
